/**
 * Created by jt on 2017/5/6.
 */
import "./index.less";
import "../../../unit/common/js/bootstrap_js/select2.min.js";
import "../../../unit/common/js/bootstrap_js/jquery.dataTables.js";
import "../../../unit/common/js/bootstrap_js/form-samples.js";
import "../../../unit/common/js/bootstrap_js/table-editable.js";

import expertListTpl from "./getExperte.handlebars";
import paginationTpl from "./paging.handlebars";

    var token = sessionStorage.getItem('token');
    if (token == null || token =='') {
        location.href = HOST_FRT+'/logins/login.html';
    }

var expertList = {
    pageNo: 1,
    pageSize: 20,
    maxPage: 1,
    isFirstPage: false,
    isLastPage: false,
    total: 0,
    data:{},
    init: function(){
        this.getExpertData()
            .then(this.renderexpertList)
            .then(this.renderPagination)
            .then(this.bindEvent);
    },
    getExpertData: function() {
        return new Promise((resolve, reject)=>{
                let self = this;
        $.ajax({
            url: HOST_ADDR + `/cpmp/expt/queryByConds/${self.pageNo}/${self.pageSize}`,
            type: 'post',
            dataType: 'json',
            headers: {
                'access_token': token,'login_type':'ums'
            },
            data:JSON.stringify(self.data),
            contentType: "application/json",
            success: function (resp) {
                if (resp.success) {
                    console.log(resp);
                    resolve(resp);
                }
                else {
                    alert(resp.msgInf);
                }
            },
            error: function (err) {
                console.log(err);
            }
        });

    });

    },
    // 渲染列表

    renderexpertList: function(resp){
        let self = expertList;
        // 处理数据begin
        self.total = resp.data.count;
        self.isFirstPage = self.pageNo === 1;
        self.maxPage = Math.ceil(self.total / self.pageSize);

        // 处理数据end
        if(self.pageNo * self.pageSize >= self.total){
            self.isLastPage = true;
        }else{
            self.isLastPage = false;
        }

        let resultHtml = expertListTpl({expertList: resp.data.list});
        $('tbody').html(resultHtml);
    },

    // 渲染分页
    renderPagination: function(){
        let self = expertList;
        let pageList = [];
        for(let i=0; i<self.maxPage; i++){
            pageList.push({idx: i+1});
        }
        console.log(self.total);
        let paginationHtml = paginationTpl({
            begin: (self.pageNo-1) * self.pageSize + 1,
            end: self.isLastPage ? self.total : self.pageNo * self.pageSize,
            total: self.total,
            isLastPage: self.isLastPage,
            isFirstPage: self.isFirstPage,
            pageList: pageList

        });
        $('.J_pagination').html(paginationHtml);
        $('.page-item').each((index,item)=>{
            if($(item).data('index')===self.pageNo){
            console.log(this);
            $(item).addClass('active');
        }
            //最多显示7个页码
            if (Math.abs($(item).data('index')-self.pageNo) > 3) {
                $(item).css('display','none');
            }
    });
    },

    // 绑定事件
    bindEvent: function(){
        let self = expertList;
        $('.J_prev').unbind().click(function(){
            if(self.pageNo > 1){
                self.pageNo = self.pageNo -1;
                self.renderList();
            }
        });
        $('.J_next').unbind().click(function(){
            if(self.pageNo < self.maxPage){
                self.pageNo = self.pageNo + 1;
                self.renderList();
            }

        });

        //首尾页
        $('.isFirst').unbind().click(function(){
            if(self.pageNo != 1){
                self.pageNo = 1;
                self.renderList();
            }
        });
        $('.isLast').unbind().click(function(){
            if(self.pageNo != self.maxPage){
                self.pageNo = self.maxPage;
                self.renderList();
            }
        });

        $('.page-item').unbind().click(function(){
            let $item = $(this);

            if(!$item.hasClass('active')){
                self.pageNo = $item.data('index');
                self.renderList();
            }
        });

        //搜索
        jQuery('.searchExp').unbind().click(function(){
            var searNam = jQuery('.searNam').val();
            self.data={};
            if (searNam != '' && searNam != null) {
                self.data.exptNam = searNam;
            }
            self.renderList();
        });

        //删除整行
        jQuery('.delete').click(function () {
            var _this = jQuery(this);
            var projId = _this.parent('td').siblings('td').eq(0).text();
            // alert(projId)
            jQuery.ajax({
                url: HOST_ADDR+'/cpmp/expt/del/'+projId,
                type: 'get',
                // data: JSON.stringify(data),
                dataType: 'json',
                contentType:"application/json",
                headers: {
                    'access_token': token,'login_type':'ums'
                },
                success: function(resp){
                    if (!resp.success) {
                        console.log(resp.msgCod+' '+resp.msgInf);
                        return;
                    }
                    // console.log(resp);
                    _this.parent('td').parent('tr').remove();
                },
                error:function(err){
                    console.log(err);
                }
            });
        });

        //重置密码
        jQuery('.reset').click(function () {
            var _this = jQuery(this);
            var projId = _this.parent('td').siblings('td').eq(0).text();
            // alert(projId)
            jQuery.ajax({
                url: HOST_ADDR+'/cpmp/expt/resetPsw/'+projId,
                type: 'get',
                // data: JSON.stringify(data),
                dataType: 'json',
                contentType:"application/json",
                headers: {
                    'access_token': token,'login_type':'ums'
                },
                success: function(resp){
                    if (!resp.success) {
                        console.log(resp.msgCod+' '+resp.msgInf);
                        return;
                    }
                    alert('重置密码成功！');
                },
                error:function(err){
                    console.log(err);
                }
            });
        });

    },

    // 渲染列表
    renderList(){
        this.getExpertData()
            .then(this.renderexpertList)
            .then(this.renderPagination)
            .then(this.bindEvent);
    }
};

App.init();
expertList.init();
jQuery('.logOut').attr('href','../logins/login.html');